#include <stdio.h>
#include <time.h>

int mdays[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

char *weeks[] = {"Sun","Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};

enum sunsort {sunIsFirst, sunIsEnd};

int dayofweek(int y, int m, int d)
{
    if (m == 1 || m == 2)
        (y--, m += 12);

    return (y + y/4 - y/100 + y/400 + (13*m+8)/5 + d) % 7;
}

int is_leap(int y)
{
    return y % 400 == 0 || (y % 4 == 0 && y % 100 != 0);
}

int monthdays(int y, int m)
{
    if (m -- != 2)
        return mdays[m];

    return mdays[m] + is_leap(y);
}

void put_calendar(int y, int m, enum sunsort sort)
{
    int i=0;
    int wd = dayofweek(y, m, 1);
    int days = monthdays(y, m);

    for (int i=0; i<7; ++i) {
        printf(" %s", weeks[(i+sort) % 7]);
    }
    putchar('\n');

    printf("-----------------------------\n");

    printf("%*s", 4 * (sort == sunIsFirst? wd: (wd-1+7) % 7), "");

    for (int i=1; i<=days; ++i) {
        printf("  %02d", i);

        //(sort-1+2)%2 equivalence sort == 0? 1: 0
        if (((sort-1+2)%2 + wd++) % 7 == 0)
            printf("\n\n");
    }

}

int main(void) {
    int y,m;

    printf("显示日历.\n");
    printf("年:");
    scanf("%d", &y);

    printf("月:");
    scanf("%d", &m);

    putchar('\n');

    put_calendar(y, m, sunIsEnd);

    putchar('\n');

    return 0;
}
